﻿
/***分享功能封装***/
/*
* version:3.0
* 使用说明
* 1.添加手机版分享到APP功能，目前仅仅测试或android
*/
(function (window) {

    //页面解析到当前为止所有的script标签
    var js = document.scripts;
    //js[js.length - 1] 就是当前的js文件的路径
    var path = js[js.length - 1].src.substring(0, js[js.length - 1].src.lastIndexOf("/") + 1);

    var UA = navigator.userAgent;
    var isIpad = /(iPad).*OS\s([\d_]+)/.test(UA);
    var isIpod = /(iPod)(.*OS\s([\d_]+))?/.test(UA)
    var isIphone = !isIpad && /(iPhone\sOS)\s([\d_]+)/.test(UA);
    var isIos = isIpad || isIpod || isIphone;
    var isAndroid = /(Android);?[\s\/]+([\d.]+)?/.test(UA);
    var isWechat = /micromessenger/i.test(UA);
    var isQQ = /QQ\/([\d\.]+)/.test(UA);
    var isQZone = /Qzone\//.test(UA);
    var isQQMBrowser = /MQQBrowser/i.test(UA) && !isWechat && !isQQ;
    var isUCMBrowser = /UCBrowser/i.test(UA)
    var isBaiduMBrowser = /mobile.*baidubrowser/i.test(UA);
    var isSogouMBrowser = /SogouMobileBrowser/i.test(UA);
    var isBaiduApp = /baiduboxapp/i.test(UA);

    function noop() { }

    function loadJs(src, callback) {
        var ref = document.getElementsByTagName('script')[0];
        var script = document.createElement('script');
        script.src = src;
        script.async = true;
        ref.parentNode.insertBefore(script, ref);
        script.onload = callback;
    }
    function loadCss(href, callback) {
        var link = document.createElement('link');
        link.href = path + href;
        link.rel = 'stylesheet';
        link.async = true;
        document.body.appendChild(link);
        link.onload = callback;
    }
    var Base64 = {
        _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
        encode: function (a) {
            var b,
                c,
                d,
                e,
                f,
                g,
                h,
                i = '',
                j = 0;
            for (a = Base64._utf8_encode(a); j < a.length;)
                (b = a.charCodeAt(j++)),
                    (c = a.charCodeAt(j++)),
                    (d = a.charCodeAt(j++)), (e = b >> 2),
                    (f = ((3 & b) << 4) | (c >> 4)),
                    (g = ((15 & c) << 2) | (d >> 6)),
                    (h = 63 & d), isNaN(c) ? (g = h = 64) : isNaN(d) && (h = 64),
                    (i = i + this._keyStr.charAt(e) + this._keyStr.charAt(f) + this._keyStr.charAt(g) + this._keyStr.charAt(h));
            return i;
        },
        _utf8_encode: function (a) {
            a = a.replace(/\r\n/g, '\n')
            for (var b = '', c = 0; c < a.length; c++) {
                var d = a.charCodeAt(c);
                d < 128 ? (b += String.fromCharCode(d)) : d > 127 && d < 2048 ? ((b += String.fromCharCode((d >> 6) | 192)), (b += String.fromCharCode((63 & d) | 128))) : (
                    (b += String.fromCharCode((d >> 12) | 224)),
                    (b += String.fromCharCode(((d >> 6) & 63) | 128)),
                    (b += String.fromCharCode((63 & d) | 128))
                );
            }
            return b;
        },
    }


    /**
     * Pc 版分享 按钮处理定义
     */
    var pcShare = {
        /**************新浪微博分享**************/
        /*
        *url:分享链接
        *title:分享标题
        *pic:分享的图片地址，目前只能单张图片
        */
        weibo: function (data) {
            var _this = this;
            this.data = data;
            //当前使用的appkey
            var appkey = '';//创建网站后的appkey
            var sinaUrl = 'http://service.weibo.com/share/share.php?';

            var params = [];
            params.push('url=', _this.encodeURIComponent(data.url));
            params.push('&appkey=', _this.encodeURIComponent(appkey));
            params.push('&title=', _this.encodeURIComponent(data.title));
            params.push('&pic=', _this.encodeURIComponent(data.img_url));
            //if (source) {
            //    params.push('&source=', _this.encodeURIComponent(source));
            //}
            //if (sourceUrl) {
            //    params.push('&sourceUrl=', _this.encodeURIComponent(sourceUrl));
            //}

            sinaUrl += params.join('');
            _this.open(sinaUrl);
        },
        /**************分享到QQ 空间**************/
        /*
        *url: 原文连接
        *title:标题
        *pics:代表图片（可以是多张）
        *summary:摘要
        *desc:分享理由
        *site:分享来源 如：腾讯网(可选)
        *showcount:是否显示分享总数,显示：'1'，不显示：'0' 
        */
        qZone: function (data) {
            var _this = this;
            this.data = data;
            var appkey = '';
            var qzoneUrl = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?';

            var params = [];
            params.push('appkey=', appkey);
            params.push('&url=', _this.encodeURIComponent(data.url));
            params.push('&title=', _this.encodeURIComponent(data.title));
            params.push('&pics=', _this.encodeURIComponent(data.img_url));
            params.push('&summary=', _this.encodeURIComponent(data.description));
            params.push('&desc=', _this.encodeURIComponent(data.description));
            // if (site)
            //     params.push('&site=', _this.encodeURIComponent(data.from));

            qzoneUrl += params.join('');
            _this.open(qzoneUrl);
        },
        /**************分享到 人人网**************/
        /*
        *resourceUrl:分享的资源Url
        *srcUrl:分享的资源来源Url,默认为header中的Referer,如果分享失败可以调整此值为resourceUrl试试
        *pic:分享的主题图片Url
        *title:分享的标题
        *description:分享的详细描述
        */
        renrenShare: function (url, title, pic, desc, resourceUrl) {
            var _this = this;
            var appkey = '';//创建网站后的 appkey
            var renrenUrl = 'http://widget.renren.com/dialog/share?';

            var params = [];
            params.push('appkey=', _this.encodeURIComponent(appkey));
            params.push('&srcUrl=', _this.encodeURIComponent(url));
            if (title)
                params.push('&title=', _this.encodeURIComponent(title));
            if (pic)
                params.push('&pic=', _this.encodeURIComponent(pic));
            if (desc)
                params.push('&description=', _this.encodeURIComponent(desc));
            params.push('&resourceUrl=', _this.encodeURIComponent(resourceUrl));

            renrenUrl += params.join('');
            _this.open(renrenUrl);
        },
        /**************分享到 网易平台**************/
        /*
        *appkey ：你在易信开放平台申请的appId，审核通过的应用将在内容来源处显示你填写的应用名称，否则显示“未审核应用”。用户在分享界面不可修改。
        *type ：图片分享类型的分享请设置为"webpage"。用户在分享界面不可修改。
        *title ：从你的应用中预设分享出去的标题。用户在分享界面不可修改。
        *desc ：从你的应用中预设分享出去的文本，用户在分享界面不可修改。
        *userdesc ：你的应用为用户预设的输入文本，用户可自行修改。
        *pic ：缩略图url，建议尺寸300px*300px。用户在分享界面不可修改。
        *url ：该图文资源对应的网页地址url，易信中点击该消息时将调用webview进行访问。用户在分享界面不可修改。该字段必需。
        */
        yixinShare: function (url, title, pic, desc) {
            var _this = this;
            var appkey = '';//创建网站后的 appkey
            var shareUrl = 'http://open.yixin.im/share?';

            var params = [];
            params.push('appkey=', _this.encodeURIComponent(appkey));
            params.push('&url=', _this.encodeURIComponent(url));
            params.push('&type=webpage');
            if (title)
                params.push('&title=', _this.encodeURIComponent(title));
            if (pic)
                params.push('&pic=', _this.encodeURIComponent(pic));
            if (desc)
                params.push('&desc=', _this.encodeURIComponent(desc));

            shareUrl += params.join('');
            _this.open(shareUrl);
        },
        //指定地址弹出窗口,位于屏幕中间,
        //如果失败，新窗口打开
        open: function (url) {
            var screen = window.screen;
            var defaults = this.opts;
            if (!window.open(url, 'shareHelper', ['toolbar=0,status=0,resizable=1,width=', defaults.width, ',height=', defaults.height, ',left=', (screen.width - defaults.width) / 2, ',top=', (screen.height - defaults.height) / 2].join(''))) {
                window.open(url, '_blank');
            }
        },
        //加密参数
        encodeURIComponent: function (str) {
            return window.encodeURIComponent(str);
        }
    }

    /**
     * 手机版分享处理
     */
    var commamdMap = {
        wechatTimeline: 8, //朋友圈
        wechatFriend: 1,//微信 好友
        qqFriend: 4,//QQ好友
        qZone: 3,//QQ空间
        weibo: 11,//微博
        copyUrl: 10,//复制链接
        more: 5,
        generateQRCode: 7,
        defaultCommand: undefined,
    };
    var shareData = {
        title: '分享标题',
        description: '分享描述',
        url: '',
        img_url: [],
        from: 'tianma3798'
    };

    /**
     * 手机版浏览器分享定义
     */
    var mobileShare = {
        //微信朋友圈
        wechatTimeLine: function (data) {
            data.to_app = commamdMap.wechatTimeline;
            this.share(data);
        },
        //微信 好友
        wechatFriend: function (data) {
            data.to_app = commamdMap.wechatFriend;
            this.share(data);
        },
        //QQ好友
        qqFriend: function (data) {
            data.to_app = commamdMap.qqFriend;
            this.share(data);
        },
        //QQ空间
        qZone: function (data) {
            data.to_app = commamdMap.qZone;
            this.share(data);
        },
        //微博
        weibo: function (data) {
            data.to_app = commamdMap.weibo;
            this.share(data);
        },
        //复制链接
        copyUrl: function (data) {
            data.to_app = commamdMap.copyUrl;
            this.share(data);
        },
        //分享
        share: function (data) {
            if (typeof browser == 'undefined')
                loadJs('https://jsapi.qq.com/get?api=app.share', function () {
                    if (typeof browser == 'undefined') {
                        alert('获取browser对象失败');
                        return;
                    }
                    browser.app.share({
                        title: data.title,
                        description: data.description,
                        url: data.url,
                        img_url: data.img_url[0],
                        from: data.from,
                        to_app: data.to_app
                    });
                });
            else
                browser.app.share({
                    title: data.title,
                    description: data.description,
                    url: data.url,
                    img_url: data.img_url[0],
                    from: data.from,
                    to_app: data.to_app
                });
        }
    };

    /**
     * 自动生成分享分享内容
     * @param {*分享内容参数} options 
     */
    var shareHelper = function (id, options) {
        var _this = this;
        //定义窗口的大小
        var defaults = {
            width: 620,
            height: 450,
            command: undefined, //定义分享的命令
            shareData: shareData
        }
        if (options == undefined) options = {};
        this.opts = Object.assign(defaults, options);

        //console.info(this.opts);
        this.elem = document.getElementById(id);
        pcShare.opts = this.opts;

        _this.init();
    }
    shareHelper.prototype = {
        init: function () {
            //绑定处理和事件
            var _this = this;
            var _opts = this.opts;
            var _elem = _this.elem;
            var text = _this.getItem('share-text');
            text.innerText = '分享到';
            _elem.appendChild(text);


            if (_this.isMobile()) {
                //提前加载js
                if (typeof browser == 'undefined')
                    loadJs('https://jsapi.qq.com/get?api=app.share', function () {
                        if (typeof browser == 'undefined') {
                            alert('获取browser对象失败，此模式下不能分享');
                            return;
                        }
                    });

                //手机版 绑定
                var commands = ['wechatFriend', 'wechatTimeLine', 'qZone', 'qqFriend', 'weibo'];
                //内部样式 
                for (var index = 0; index < commands.length; index++) {
                    var element = commands[index];
                    _elem.appendChild(_this.getItem('share-item  share-' + element.toLowerCase(), element));
                }
            } else {
                //PC绑定
                var commands = ['qZone', 'weibo'];
                //内部样式 
                for (var index = 0; index < commands.length; index++) {
                    var element = commands[index];
                    _elem.appendChild(_this.getItem('share-item  share-' + element.toLowerCase(), element));
                }
            }
        },
        //获取按钮项 
        getItem: function (cla, eventName) {
            var _this = this;
            var span = document.createElement('span');
            span.className = cla;
            if (eventName)
                span.onclick = function () {
                    _this[eventName]();
                }
            return span;
        },
        //判断是否是手机版
        isMobile: function () {
            if (isWechat)
                return false;
            return isAndroid || isIos;
        },
        //绑定微信朋友圈
        wechatTimeLine: function () {
            var _this = this;
            var data = _this.opts.shareData;
            if (_this.isMobile()) {
                mobileShare.wechatTimeLine(data);
            } else {
                console.error('PC版目前不支持微信朋友圈。');
            }
        },
        //绑定微信好友
        wechatFriend: function () {
            var _this = this;
            var data = _this.opts.shareData;
            if (_this.isMobile()) {
                mobileShare.wechatFriend(data);
            } else {
                console.error('PC版目前不支持微信好友');
            }
        },
        //绑定QQ空间
        qZone: function () {
            var _this = this;
            var data = _this.opts.shareData;
            if (_this.isMobile()) {
                mobileShare.qZone(data);
            } else {
                pcShare.qZone(data);
            }
        },
        //绑定QQ好友
        qqFriend: function () {
            var _this = this;
            var data = _this.opts.shareData;
            if (_this.isMobile()) {
                mobileShare.qqFriend(data);
            } else {
                console.info('目前PC版不支持分享到QQ好友');
            }
        },
        //绑定微博
        weibo: function () {
            var _this = this;
            var data = _this.opts.shareData;
            if (_this.isMobile()) {
                mobileShare.weibo(data);
            } else {
                pcShare.weibo(data);
            }
        }
    }
    window.shareHelper = shareHelper;

})(window);

